//
//  KomplectsViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/27/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class KomplektsViewController: UIViewController, Alertable {
    
    // MARK: - Outlets
    
    private lazy var tableView: UITableView = {
        let table = UITableView()
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .none
        table.register(KomplektCell.self, forCellReuseIdentifier: "KomplektCell")
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = .white
        return table
    }()
    
    private var spinnerView = SpinnerView()
    
    // MARK: - Props
    
    public var carId: Int!
    private var viewModel = KomplektViewModel()
    
    private var isLoading: Bool = false {
        didSet {
            view.isUserInteractionEnabled = !isLoading
            isLoading ? spinnerView.startAnimating() : spinnerView.stopAnimating()
        }
    }
    
    // MARK: - Actions
    
    @objc private func goBack (sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    // MARK: - Init
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addViews()
        self.loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setUpNavBar()
    }
}


// MARK: - Methods

extension KomplektsViewController {
    private func loadData () {
        self.isLoading = true
        viewModel.loadData(carID: self.carId) { (result) in
            self.isLoading = false
            switch result {
            case .failure(let err):
                switch err {
                case .general:
                    self.showAlert("Упс...", "Неизвестная ошибка")
                case .parameter(let msg):
                    self.showAlert("Упс...", msg)
                }
            case .success(_):
                self.tableView.reloadData()
            }
        }
    }
}



// MARK: - Table View Configuration

extension KomplektsViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.data.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let inital = viewModel.data[indexPath.row].isExpanded
        viewModel.data[indexPath.row].isExpanded.toggle()
        
        tableView.reloadRows(at: [indexPath], with: inital ? .bottom : .top)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KomplektCell") as! KomplektCell
        cell.data = viewModel.data[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}


// MARK: - UI

extension KomplektsViewController {
    
    private func addViews () {
        self.view.addSubview(tableView)
        self.view.addSubview(spinnerView)
        
        spinnerView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    private func setUpNavBar() {
        self.navigationItem.title = "Комплектации"
        self.addBackIcon()
    }
    
    private func addBackIcon () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        navigationItem.leftBarButtonItem = backButton
    }
}
